//
//  MJRefresh+Extension.swift
//  Lease_IOS
//
//  Created by Mr.wang on 2018/12/20.
//  Copyright © 2018 Mr.wang. All rights reserved.
//

import RxCocoa
import RxSwift
import MJRefresh

class MJRefreshBaseColorHeader : MJRefreshNormalHeader {
    
    let headerBackgroundView = UIView(frame: CGRect(x: 0, y: -SCREEN_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = APPConfig.baseColor
        headerBackgroundView.backgroundColor = APPConfig.baseColor
        self.stateLabel?.textColor = .white
        self.lastUpdatedTimeLabel?.isHidden = true
//        self.activityIndicatorViewStyle
//        self.loadingView?.color = .white
        self.activityIndicatorViewStyle = .white
        self.addSubview(headerBackgroundView)
    }
    
    func setBaseColor(_ color: UIColor) {
        self.backgroundColor = color
        headerBackgroundView.backgroundColor = color
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


extension Reactive where Base: MJRefreshComponent {
    
    public var beginRefresh: Observable<Void> {
        return base.rx
            .sentMessage(#selector(MJRefreshComponent.executeRefreshingCallback))
            .map{ _ in }
    }
    
    public var isRefreshing: Binder<Bool> {
        return Binder(self.base) { refreshControl, loading in
            if !loading {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
                    refreshControl.endRefreshing()
                })
            }
        }
    }
    
    public var state: Binder<MJRefreshState> {
        return Binder(self.base) { refresh, state in
            refresh.state = state
        }
    }
    
}

extension ObservableType where Element == Int {
    
    public var refreshState: Observable<MJRefreshState> {
        return self.map { number -> MJRefreshState in
            if number == 0 {
                return .noMoreData
            } else {
                return .idle
            }
        }
    }
    
}
